# -*- coding:utf-8 -*-
import random
import datetime

from google.appengine.api import users
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import memcache

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseForbidden
from django.http import HttpResponseNotFound

from django.shortcuts import render_to_response
from django.template.loader import render_to_string

from blog.models import *
from blog.utils import *
from blog.forms import *
from blog.utils import _cntime

@cache_page(60*10)
def index(request):
    """
    Show the index page
    
    request -- the HttpRequest object
    """
    # 通过 'VND.WAP.WML' 判断是否为WAP浏览器
    if 'VND.WAP.WML' in request.META.get('HTTP_ACCEPT').upper():
        return HttpResponseRedirect('/wap')

    categories = Category.all()
    new_archives = Archive.all().order('-pub_date')[:5]
    new_comments = Comment.all().order('-date')[:6]
    top_archives = Archive.all().order('-view_nums')[:5]
    new_mblogs = MBlog.all().order('-pub_date')[:5]
    mblog_count = MBlog.all().count()
    mblog_comment_count = Comment.all().filter('mblog !=',None).count()
    context =dict(categories=categories,
            new_archives=new_archives,
            top_archives=top_archives,
            new_mblogs = new_mblogs,
            new_comments =  new_comments,
            mblog_count = mblog_count,
            mblog_comment_count = mblog_comment_count,
            )
    return render_to_response('index.html',context)

@admin_required
@clear_cache()
def add_mblog(request):
    """发表新微博"""
    if request.method == 'POST':
        content = request.POST.get('content')
        if not content:
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

        mblog = MBlog(content=content,pub_date=_cntime())
        mblog.put()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

@admin_required
@clear_cache()
def add_category(request):
    """添加新分类"""
    if request.method == 'GET':
        return render_to_response('add_category.html')

    elif request.method == 'POST':
        name = request.POST.get('name')
        if not name:
            return render_to_response('add_category.html', {'error':'必填'})
        
        key_name = name.replace(' ', '_')
        # 把空格替换为 _ 
        if Category.get_by_key_name(key_name):
            return render_to_response('add_category.html', dict(error=u'已存在'))

        category = Category(name=name, key_name=key_name)
        category.put()

        return HttpResponseRedirect(category.get_absolute_url().encode('utf-8'))

@admin_required
@clear_cache()
def edit_category(request,name=''):
    """修改分类名字"""
    category = Category.get_by_key_name(name)

    if not category:
        return HttpResponseRedirect('/not_found')

    if request.method == 'GET':
        return render_to_response('edit_category.html',dict(category=category))

    elif request.method == 'POST':
        name = request.POST.get('name')
        if not name:
            return render_to_response('edit_category.html',dict(error=u'required'),category=category)
        
        category.name = name
        category.put()
        return HttpResponseRedirect(category.get_absolute_url())


@clear_cache()
def delete_category(request,name=''):
    if not users.is_current_user_admin():
        return HttpResponseForbidden()

    if not request.META.get('HTTP_REFERER', '').startswith('http://'+request.get_host()):
        # 禁止非本域的请求
        return HttpResponseForbidden();

    category = Category.get_by_key_name(name) 
    if not category:
        return HttpResponseRedirect('/not_found')

    category.delete()
    return HttpResponseRedirect('/')

@cache_page(10*60 ,vary_user=True)
def category(request, name=''):
    """
    @param name:  分类 keyname
    """
    if request.method == 'GET':
        # /category/id
        category = Category.get_by_key_name(name)
        if not category:
            return HttpResponseRedirect('/not_found')
        
        archives = category.archives.order('-pub_date')
        context = dict(category = category,
                archives = archives
                )
        return render_to_response('category.html', context )

    elif request.method == 'DELETE':
        if not users.is_current_user_admin():
            return HttpResponseForbidden()

        category = Category.get_by_key_name(name)
        if not category:
            return HttpResponseRedirect('/not_found')
        
        if category.archives.count() > 0:
            pass
        category.delete()

def tag(request,name=''):
    tag = Tag.get_by_key_name(name)
    if not tag:
        return HttpResponseRedirect('/not_found')

    archives = [Archive.get(key) for key in tag.archives ]
    return render_to_response('tag.html',dict(tag=tag,archives=archives))

@admin_required
@clear_cache()
def add_archive(request):
    if request.method == 'GET':
        form = ArchiveForm()
        return render_to_response('edit_archive.html',dict(form=form))
    elif request.method == 'POST':
        form = ArchiveForm(request.POST)
        if not form.is_valid():
            return render_to_response('edit_archive.html',dict(form=form))
        archive =  form.save()
        archive.pub_date = _cntime()
        archive.put()

        archive.process_tags()

        archive.category.posts += 1
        archive.category.put()

        return HttpResponseRedirect(archive.get_absolute_url())

@admin_required
@clear_cache()
def edit_archive(request,id):
    archive = Archive.get_by_id(int(id)) 
    if not archive:
        return HttpResponseRedirect('/not_found')
    if request.method == 'GET':
        form = ArchiveForm(instance=archive)
        context = dict(form=form,edit=True,id=archive.key().id())
        return render_to_response('edit_archive.html',context)

    elif request.method == 'POST':
        form = ArchiveForm(request.POST)
        if not form.is_valid():
            context = dict(form=form,edit=Ture,id=archive.key().id())
            return render_to_response('edit_archive.html',context)
        archive.title = form.cleaned_data['title']
        archive.categorie = form.cleaned_data['category']
        archive.content = form.cleaned_data['content']
        archive.tags = form.cleaned_data['tags']
        archive.save()
        archive.process_tags()
        
        return HttpResponseRedirect(archive.get_absolute_url())

@clear_cache()
def delete_archive(request,id):
    if not users.is_current_user_admin():
        return HttpResponseForbidden()

    if not request.META.get('HTTP_REFERER','None').startswith('http://'+request.get_host()):
        return HttpResponseForbidden();

    archive = Archive.get_by_id(int(id))
    if not archive:
        return HttpResponseRedirect('/not_found')
    archive.delete()
    return HttpResponseRedirect(archive.category.get_absolute_url())

@cache_page(60*10 ,vary_user=True)
def archive(request, id=-1):
    """
    the Archive RESTful handler

    id -- archive_id /archive/id
    """
    archive = Archive.get_by_id(int(id))
    if not archive:
        return HttpResponseRedirect('/not_found')
    archive.view_nums += 1
    archive.put()
    user = users.get_current_user()
    if user:
        comment_form = CommentForm( instance=Comment(
            name= user.nickname(),
            email = user.email(),
            content = u'说点啥呗',
        ))
    else:
        comment_form = CommentForm()
    if not archive:
        return HttpResponseRedirect('/not_found')

    
    context = dict(archive=archive,
        comment_form=comment_form,
        is_admin=users.is_current_user_admin(),
        )

    if archive.tags:
        tags = archive.tags.split(',')
        context['tags'] = tags

    return render_to_response('archive.html',context)

@cache_page(60)
def sidebar(request):
    categories = Category.all().order('posts')
    populars = Archive.all().order('-view_nums')[:7]
    archives = Archive.all().order('-pub_date')[:10]
    comments = Comment.all().order('-date')[:10]
    tags = Tag.all()
    context = dict(categories=categories,
            archives=archives,
            comments=comments,
            populars=populars,
            author = Author.get_or_insert('author'),
            blog = Blog.get_or_insert('blog'),
            tags = tags,
            )
    return render_to_response('sidebar.html' ,context )
    
@clear_cache()
def add_comment(request,archive_id):
    """添加评论"""
    if not request.method == 'POST':
        return HttpResponseForbidden()

    archive = Archive.get_by_id(int(archive_id))
    if not archive:
        return HttpResponseRedirect('/not_found')
    
    form = CommentForm(request.POST)
    if not form.is_valid():
        return render_to_response('archive.html',
            dict(archive=archive, comment_form=form)
        )
    comment = form.save()
    avatars = [ '/static/avatars/avatar_%d.jpg' % i for i in range(1,36)]
    comment.avatar = random.choice(avatars)
    comment.archive = archive
    comment.date = _cntime()
    comment.put()

    return HttpResponseRedirect(archive.get_absolute_url())
     
@admin_required
@expose(type='json')
def upload(request):
    """
    @description: 上传图片
    @return: 图片地址
    """
    if not request.method == 'POST':
        return dict(success=False,data='Error')

    image = request.FILES.get('image')
    if not image:
        return dict(success=False,data='必须上传个图片')
    if image.size > 1024*1024*1:
        return dict(success=False,data='图片太大啦')
    if not image.name[-3:].lower() in ['jpg','gif','png']:
        return dict(success=False,data='不支持的图片类型')
    
    model = Image(name=image.name,
        content_type = image.content_type ,
        data = image.read(),
        )

    model.put()

    return dict(success=True,
        data='http://%s%s' % ( request.get_host(), model.get_absolute_url()) 
    )

@cache_page(60*60*6)
def image(request, key):
    """获取图片"""
    image = Image.get(db.Key(key))
    if not image:
        return HttpResponseNotFound()

    return HttpResponse(image.data,image.content_type)

def login(request):
    return HttpResponseRedirect(
        users.create_login_url(request.META.get('HTTP_REFERER','/'))
    )

@clear_cache()
@admin_required
def admin(request, tab=''):
    """管理页面"""
    if request.method == 'GET':
        blog = BlogForm(instance=Blog.get_or_insert('blog'))
        author = AuthorForm(instance= Author.get_or_insert('author') )
        context = dict( blog=blog, author = author )
        return render_to_response('admin.html',context)

    elif request.method == 'POST':
        if tab == 'blog':
            blog = BlogForm(request.POST)
            if not blog.is_valid():
                author = AuthorForm(instance=Author.get_or_insert('author') )
                context = dict( blog=blog, author = author )
                return render_to_response('admin.html', context)

            model = Blog(key_name='blog',
                name = blog.cleaned_data['name'],
                description = blog.cleaned_data['description'],
                rss = blog.cleaned_data['rss'],
                sidebar = blog.cleaned_data['sidebar'],
            )
            model.put()
            
        elif tab == 'author':
            author = AuthorForm(request.POST)
            if not author.is_valid():
                blog = BlogForm(instance=Blog.get_or_insert('blog'))
                context = dict( blog=blog, author = author )
                return render_to_response('admin.html',context)
            model = Author(key_name='author',
                name = author.cleaned_data['name'],
                description = author.cleaned_data['description'],
                avatar = author.cleaned_data['avatar'],
                email = author.cleaned_data['email'],
            )
            model.put()
        else:
            return HttpResponse('nof_found')
        return HttpResponseRedirect('/admin')

        
def not_found(request):
    context=dict(referer=request.META.get('HTTP_REFERER'))
    return render_to_response('not_found.html',context)

#def wap(request):
#    archive = Archive.all().order('-pub_date')[0]
#    info = str(request.META)
#    return render_to_response('wap.html',dict(info=info))
#    return render_to_response('wap.html',dict(archive=archive),mimetype='text/vnd.wap.wml')
#    

def archive_nav(request,id,direction):
    """用于鼠标手势 上一篇 及 下一篇 导航"""
    archive = Archive.get_by_id(int(id))
    if not archive:
        return HttpResponseRedirect('/not_found')
    if direction == 'next':
        op = '<'
    else:
        op = '>'

    q = Archive.all().filter('pub_date ' + op  ,archive.pub_date )
    if direction == 'next':
        ar = q.order('-pub_date').get()
    else:
        ar = q.order('pub_date').get()
    if not ar:
        return HttpResponseRedirect('/not_found')
    
    return HttpResponseRedirect(ar.get_absolute_url())


